<?php
declare (strict_types = 1);

namespace quick\admin\http\middleware;


use app\common\model\SystemOplog;
use app\Request;
use quick\admin\library\service\NodeService;
use quick\admin\Quick;
use think\Response;

/**
 * 跨域中间件
 * Class AllowOriginMiddleware
 * @package app\http\middleware
 */
class AdminLogMiddleware
{



    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle(Request $request, \Closure $next)
    {


        $node = NodeService::instance()->getCurrent();
        $nodes = NodeService::instance()->getNodes();
        $plugin = strtolower(app()->http->getName());
        $nodeInfo = $nodes[$node] ?? [];
        // post请求记录日志，如果节点设置了日志侧跟随设置
        if(($request->isPost() && empty($nodeInfo)) || !empty($nodeInfo['is_log'])){
            $action = $node;
            $url = $request->url();

            // 排除action类的load请求
            if(strpos($url,$node.'/load') !== false){
                return $next($request);
            }
            if(!empty($nodeInfo)){
                $action = $nodeInfo['title'];
                if(!empty($nodes[$nodeInfo['pnode']])){
                    $action = $nodes[$nodeInfo['pnode']]['title'].'-'.$action;
                }
            }


            $model = new SystemOplog();
            $model->node = $node;
            $model->action = $action;
            $model->plugin = $plugin;
            $model->content = $url ;
            $model->geoip = $request->ip() ?: '127.0.0.1';
            $model->method = $request->method();

            $model->params = json_encode($request->param());
            $model->json_result = json_encode([]);
            $model->error_msg = json_encode([$request->route()]);
            $model->user_agent = $request->header('user-agent');
            $model->username = '-';
            $model->user_id = 0;
            try {

                $res = $next($request);

                $auth = Quick::getAuthService();
                $adminInfo = $auth->getUserInfo();
                $model->username = $auth->getUsername() ?: '-';
                $model->user_id = $adminInfo ? $adminInfo->user_id:0;


                /** @var Response $res */
                if($res instanceof Response){
                    $resData = $res->getData();
                    $error = [
                        'msg' => $resData['msg'] ?? '',
                        'code' => $resData['code'] ?? '',
                        'data' => $resData['data'] ?? '',
                    ];
                    $model->json_result = json_encode($error);
                    if($res->getCode() !== 200) {
                        $model->error_msg = json_encode($error);
                    }


                }
            }catch (\Exception $e){
                $model->error_msg = json_encode([
                    'msg' => $e->getMessage(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'code' => $e->getCode(),
                ]);
                $model->save();
                throw $e;
            }
            $model->save();
        }else{
            $res = $next($request);
        }


        return $res;
    }
}